<template>
  <div>
    <layout @go="go" title="配置创意">
      <resTable :list="resList"></resTable>
    </layout>
    <a-modal v-model="show" okText="确定" @ok="ok" :width="650">
      <div class="content">
        <a-form-model ref="ruleForm" :model="bulkForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="品牌名称" prop="brand">
            <a-input placeholder="请输入品牌名称, 最多11个字符" v-model="bulkForm.brand" :maxLength="11"/>
          </a-form-model-item>
          <a-form-model-item label="品牌头像" prop="userPortrait">
            <a-upload
              list-type="picture-card"
              :file-list="fileList"
              :beforeUpload="beforeUpload"
              @change="handleChange"
              @preview="handlePreview"
            >
              <div v-if="fileList.length == 0">
                <a-icon type="plus" />
                <div class="ant-upload-text"> 上传 </div>
              </div>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item label="创意标题" prop="biaoti">
            <m-textline :values="bulkForm.biaoti" title="创意标题" @change="changeTextLine" />
          </a-form-model-item>
          <a-form-model-item label="自定义" prop="custom">
            <div class="item" v-for="(item,index) in bulkForm.custom" :key="index">
              <a-input v-model="item.value" type="number" :addon-before="item.title+':'" addon-after="个" />
            </div>
          </a-form-model-item>
          <a-form-model-item label="程序化" prop="program">
            <div class="item" v-for="(item,index) in bulkForm.program" :key="index">
              <a-input v-model="item.value" type="number" :addon-before="item.title+':'" addon-after="个" />
            </div>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import layout from '../layout'
import resTable from '../resTable'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

function dataURItoBlob(base64Data) {
    // 转Blob流
    // console.log(base64Data);//data:image/png;base64,
    var byteString;
    if(base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);//base64 解码
    else{
        byteString = unescape(base64Data.split(',')[1]);
    }
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

    // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    // var ia = new Uint8Array(arrayBuffer);//创建视图
    var ia = new Uint8Array(byteString.length);//创建视图
    for(var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ia], {
        type: mimeString
    });
    return blob;
}

export default {
  data() {
    return {
      show: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      rules:{
        brand: [{required: true, message: '请输入品牌名称', trigger: 'blur' }],
        userPortrait: [{required: true, message: '请选择品牌头像', trigger: 'blur' }],
        biaoti: [{required: true, message: '请输入标题', trigger: 'blur' }],
      },
      fileList:[],
      resList:[],
      previewVisible:false,
      previewImage:'',
      bulkForm:{
        brand:'',
        userPortrait:'',  //品牌头像文件
        biaoti:[],
        custom:[
          {title:'大图',value:0,id:107, key:'datu'},
          {title:'横版',value:0,id:108, key:'heng'},
          {title:'竖版',value:0,id:111, key:'shu'},
          // {title:'直播横图',value:0,id:118, key:'zhibo'},
        ],
        program:[
          {title:'大图',value:0,id:114, key:'datu'},
          {title:'横版',value:0,id:114, key:'heng'},
          {title:'竖版',value:0,id:114, key:'shu'}
        ]
      },
    }
  },
  methods:{
    ok(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.bulkForm)
          this.resList = [
            {name:'品牌名称', value: this.bulkForm.brand},
            {name:'创意标题', value: this.bulkForm.biaoti.join('、')},
            {name:'自定义', value: this.bulkForm.custom.map(e=>e.title + e.value + '个').join('、')},
            {name:'程序化', value: this.bulkForm.program.map(e=>e.title + e.value + '个').join('、')},
          ]

          this.show = false
          this.$emit("update:form", this.bulkForm)
        } 
      })
    },
    go(){
      this.show = true
    },
    changeTextLine(val){
      let biaoti = []
      for(let i of val){
        if(i.length > 30){
          i = i.replace('！','')
          i = i.replace('：','')
        }
        biaoti.push(i.slice(0,30))
      }
      this.bulkForm.biaoti = biaoti
    },
    async beforeUpload(file){
      console.log(file)
      if(!(file.type === 'image/jpeg' || file.type === 'image/png')){
        this.$message.error('只能上传JPG/PNG文件')
        return Promise.reject()
      }
      let filePreview = await getBase64(file);
      let WHResult = await this.checkWH(filePreview)
      if(!WHResult){
        this.$message.error('请上传120*120尺寸的图片')
        return Promise.reject()
      }
      this.fileList = [{
        uid: file.uid,
        name: file.name,
        url:filePreview,
      }]
      this.bulkForm.userPortrait = {name: file.name,blob:dataURItoBlob(filePreview)}
      return Promise.reject()
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    checkWH(base64Data){
      // 判断图片宽高
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = function() {
          // console.log(this.width, this.height)
          if (this.width == 120 && this.height == 120) { // 上传图片的宽高与传递过来的限制宽高作比较，超过限制则调用失败回调
            resolve(true);
          } else {
            resolve(false);
          }
        };
        image.onerror = reject;
        image.src = base64Data;
      });
    },
    handleChange({ fileList }){
      this.fileList = fileList
      if(fileList.length == 0){
        this.bulkForm.userPortrait = {name: '', blob: ''}
      }
    },
  },
  components:{layout, resTable},
}
</script>

<style lang="less" scoped>
.content{
  overflow-y: auto;
  overflow-x: hidden;
  height: 600px;
}
.item{
  width: 200px;
}
/deep/ .mui-textline-main-title, /deep/ .mui-textline .veui-textarea{
  width: 450px;
}
</style>
